# author: zhanghao
# time: 2023-12-26
# info: 这是主函数文件

# This is a pokemon Python script.
from PyQt6.QtWidgets import QFileDialog, QTableWidgetItem, QTableWidget, QAbstractItemView, QInputDialog
from PyQt6 import QtCore, QtWidgets
from PyQt6.QtGui import QFont, QIcon, QBrush, QColor
from PyQt6.QtCore import QSize

from domain.table_info import TableInfo
from domain.signal_unit import SignalUnit
from helper.status import Status
from ui.pokemon_ui import Ui_pokemon
from helper.file_helper import FileHelper
from helper.event_type import EventType
from core.manual_dialog import ManualDialog
from core.master import Master
from config.logger import Logger
from config.config import Config
from multiprocessing import Pipe

import os


class Pokemon(Ui_pokemon):
    logger = Logger().get()

    config: Config

    # 核心处理类
    master: Master

    # 表格数据
    table_data = []

    # 加载的文件信息
    file_arr = []

    manual_dialog: ManualDialog

    conn_main: Pipe

    def __init__(self, conn_main, config: Config):
        self.config = config
        self.table_data: list[TableInfo] = []
        self.conn_main = conn_main
        self.master = Master(conn_main)

    def setupUi(self, pokemon):
        # 设置ui
        Ui_pokemon.setupUi(self, pokemon)

        # 绑定事件
        self.bindEvent()

        # 设置版本
        self.setVersion(self.config.getVersion())

        # 调整界面
        self.glorifyInterface()

        # 调整表格
        self.adjustTableWidget()

    def setVersion(self, version):
        _translate = QtCore.QCoreApplication.translate
        self.label_version_edit.setText(_translate("pokemon", version))

    # event-清空
    def optClearWindows(self):
        self.adjustTableWidget()

        self.file_arr.clear()
        self.table_data.clear()
        self.tableWidget.clearContents()
        self.tableWidget.setRowCount(0)
        self.label_total_edit.setText(str(0))
        self.label_failed_edit.setText(str(0))
        self.label_finished_edit.setText(str(0))
        self.updateButtonStatus(True)

    # event-打开文件
    def optOpenFileClick(self):
        folder = QFileDialog.getExistingDirectory()
        if not folder:
            return
        folder_files = FileHelper.fetchDirFile(folder)

        # 设置文件信息到列表展示
        idx = len(self.table_data) + 1
        for file in folder_files:
            if file not in self.file_arr:
                self.table_data.append(TableInfo(idx, file, Status.WAIT_PROCESS))
                self.file_arr.append(file)
                idx += 1

        # 刷新数据展示
        self.refreshStaticData()

        # 刷新表格
        self.refreshTableWidget()

    # event-开始处理
    def optProcessClick(self):
        self.updateButtonStatus(False)
        self.optProcessThread()
        self.master.signal.connect(self.signalProcess)

    def signalProcess(self, signal_unit: SignalUnit):
        self.logger.info(signal_unit)
        if not signal_unit:
            return

        if signal_unit.event_type == EventType.START_PROCESS:
            self.eventStartProcess(signal_unit)
        elif signal_unit.event_type == EventType.END_PROCESS:
            self.eventEndProcess(signal_unit)

    def optProcessThread(self):
        self.logger.info('开始处理，文件总数：' + str(len(self.table_data)))
        if len(self.table_data) > 0:
            self.updateButtonStatus(False)
            self.master.initData(self.table_data)
            self.master.start()
        else:
            self.updateButtonStatus(True)

    # 集中绑定事件
    def bindEvent(self):
        self.pushButton_choose_file.clicked.connect(self.optOpenFileClick)
        self.pushButton_clear.clicked.connect(self.optClearWindows)
        self.pushButton_process.clicked.connect(self.optProcessClick)
        self.comboBox_status.currentIndexChanged.connect(self.optComboBoxChanged)
        self.tableWidget.itemClicked.connect(self.eventManualDeal)

    def optComboBoxChanged(self):
        index = self.comboBox_status.currentIndex()

        status = None
        if index == 1:
            status = Status.SUCCESS
        elif index == 2:
            status = Status.FAILED
        elif index == 3:
            status = Status.WAIT_PROCESS

        self.refreshTableWidget(status)

    def glorifyInterface(self):
        current_dir = os.getcwd()
        self.toolButton_ocr.setIcon(QIcon(current_dir + '/icon/open.png'))
        self.toolButton_rpa.setIcon(QIcon(current_dir + '/icon/toolbox.png'))
        self.toolButton_ocr.setIconSize(QSize(30, 30))
        self.toolButton_rpa.setIconSize(QSize(30, 30))

        self.toolButton_rpa.setHidden(True)

    def adjustTableWidget(self):
        self.tableWidget.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setFont(QFont("Arial", 12))
        self.tableWidget.setHorizontalHeaderLabels(['处理前', '状态', '处理后', '操作'])
        self.tableWidget.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.Stretch)
        self.tableWidget.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)

    def refreshTableWidget(self, status=None):
        self.tableWidget.clearContents()
        self.tableWidget.setRowCount(0)

        self.tableWidget.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeMode.ResizeToContents)
        self.tableWidget.horizontalHeader().setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeMode.ResizeToContents)
        self.tableWidget.horizontalHeader().setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeMode.ResizeToContents)
        # self.tableWidget.horizontalHeader().setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeMode.ResizeToContents)

        # 更新表格数据
        idx = 0
        for data in self.table_data:
            if status is not None and data.status != status:
                continue

            # 更新表格行数，不然显示不出来
            self.tableWidget.setRowCount(idx + 1)
            self.tableWidget.setItem(idx, 0, QTableWidgetItem(data.before_name))
            item_status = QTableWidgetItem(Status.description(data.status))
            if data.status == Status.FAILED:
                item_status.setForeground(QBrush(QColor(255, 0, 0)))
            elif data.status == Status.SUCCESS:
                item_status.setForeground(QBrush(QColor(0, 255, 0)))
            self.tableWidget.setItem(idx, 1, item_status)
            self.tableWidget.setItem(idx, 2, QTableWidgetItem(data.after_name))

            if data.operate:
                self.tableWidget.setItem(idx, 3, QTableWidgetItem('手动处理'))
            idx += 1

    def refreshSingleTableWidget(self, data: TableInfo):
        idx = data.idx - 1

        self.tableWidget.setItem(idx, 0, QTableWidgetItem(data.before_name))
        item_status = QTableWidgetItem(Status.description(data.status))
        if data.status == Status.FAILED:
            item_status.setForeground(QBrush(QColor(255, 0, 0)))
        elif data.status == Status.SUCCESS:
            item_status.setForeground(QBrush(QColor(0, 255, 0)))
        self.tableWidget.setItem(idx, 1, item_status)
        self.tableWidget.setItem(idx, 2, QTableWidgetItem(data.after_name))

        if data.operate:
            self.tableWidget.setItem(idx, 3, QTableWidgetItem('手动处理'))

    def refreshStaticData(self, finished_total=None, failed_total=None):
        self.label_total_edit.setText(str(len(self.table_data)))
        if finished_total is not None:
            self.label_finished_edit.setText(str(finished_total))
        else:
            self.label_finished_edit.setText(str(0))

        if failed_total is not None:
            self.label_failed_edit.setText(str(failed_total))
        else:
            self.label_failed_edit.setText(str(0))

    def updateButtonStatus(self, status: bool):
        self.pushButton_choose_file.setEnabled(status)
        self.pushButton_process.setEnabled(status)

    def eventStartProcess(self, signal_unit: SignalUnit):
        idx = signal_unit.task_no - 1
        self.table_data[idx].after_name = signal_unit.data_after
        self.table_data[idx].status = signal_unit.task_status
        self.table_data[idx].operate = signal_unit.manual_op

        self.refreshSingleTableWidget(self.table_data[idx])

    def eventEndProcess(self, signal_unit: SignalUnit):
        idx = signal_unit.task_no - 1
        self.table_data[idx].after_name = signal_unit.data_after
        self.table_data[idx].status = signal_unit.task_status
        self.table_data[idx].operate = signal_unit.manual_op

        self.refreshSingleTableWidget(self.table_data[idx])

        self.refreshStaticData(signal_unit.task_no, signal_unit.task_failed)

        if signal_unit.task_no == len(self.table_data):
            self.updateButtonStatus(True)

    def eventManualDeal(self, item: QTableWidgetItem):
        self.logger.info('表格被点击' + item.text() + ' ' + str(item.row()) + ' ' + str(item.column()))
        if item and item.column() == 3 and item.text() == '手动处理':
            # 处理手动重命名 1.弹框，2.获取名称，3.重命名
            self.logger.info('创建窗口')
            self.createManualWindow(item)

    def createManualWindow(self, click_item: QTableWidgetItem):
        file_name = self.table_data[click_item.row()].before_name
        self.manual_dialog = ManualDialog(file_name)



